//
//  EmoticonManager.swift
//  KeyBoard
//
//  Created by mac on 15/12/26.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

class EmoticonManager: NSObject {
    
    
    //创建单例对象
    static let sharedEmoticonManager = EmoticonManager()
    //表情分组
    lazy var packages = [EmoticonPackages]()
    //初始化
    private override init() {
        super.init()
        //加载分组表情
        loadEmoticons()
    }
    //添加替换内容中的所有image文本
    func statuseTextToImageText(str:String,font:UIFont) ->NSAttributedString {
        let pattern = "\\[.*?\\]"
        //抓包
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        //进行多次查找
        let results = regex.matchesInString(str, options: [], range: NSRange(location: 0, length: str.characters.count))
        //倒叙遍历
        var index = results.count - 1
        //创建表情源数组
        let strM = NSMutableAttributedString(string: str)
        while index >= 0 {
            let result = results[index]
            let range = result.rangeAtIndex(0)
            let subStr = (str as NSString).substringWithRange(range)
            if let em = getEmoticonWithEmoticonText(subStr) {
                let imageText = EmoticonTextAttachment().imageTextToText(em,font: font)
                //将图片转换为 附件 -> 富文本
                strM.replaceCharactersInRange(range, withAttributedString: imageText)
            }
            index--
        }
        return strM
    }
    
    func loadEmoticons() {
        //获取bundle的地址
        let path = NSBundle.mainBundle().pathForResource("emoticons.plist", ofType: nil, inDirectory: "Emoticons.bundle")
        guard let bundlePath = path else {
            print("文件不存在")
            return
        }
        //加载成字典
        let dict = NSDictionary(contentsOfFile: bundlePath)!
        //判断packages是否有值
        if let array = dict["packages"] as? [[String:AnyObject]] {
            for item in array {
                let id = item["id"] as! String
                //获取表情的数组类型
                loadPackages(id)
            }
        }
    }
    private func getEmoticonWithEmoticonText(str: String) -> Emoticons? {
        let packages = EmoticonManager.sharedEmoticonManager.packages
        for p in packages {
            //filter  过滤 滤镜
            let emoticones =  p.emoticones.filter({ (em) -> Bool in
                //返回一个过滤条件
                return em.chs == str
            })
            
            if emoticones.count != 0 {
                return emoticones.last
            }
        }
        
        return nil
    }
    
    //根据id去假爱数组的类型
    private func loadPackages(id: String) {
        //加载图片的文件夹
        let path = NSBundle.mainBundle().pathForResource("Info.plist", ofType: nil, inDirectory: "Emoticons.bundle/" + id)
        guard let bundlePath = path else {
            print("目标文件夹不存在")
            return
        }
        let dict = NSDictionary(contentsOfFile: bundlePath)!
        let group_name_cn = dict["group_name_cn"] as! String
        let array = dict["emoticons"] as! [[String:String]]
        //模型转换
        let pack = EmoticonPackages(id: id, group_name_cn: group_name_cn, emoticons: array)
        //吧模型添加到数组中去
        packages.append(pack)
        print(packages.count)
    }
    
    
}
